#!/bin/bash

FORCE_DEPLOY=0
if [ $1 == "--force" ]; then
  FORCE_DEPLOY=1
  shift
fi

if [ $# -ne 1  ]; then
  echo "Usage: $0 [--force] hostname"
  exit 1
fi

if [ $FORCE_DEPLOY -eq 1 ]; then
  echo "Forced deployment, skipping changes this is DANGERROUS!!";
else
  if [ $1 = "monitor" ]; then
    echo "Checking for preconditions when deploying to PRODUCTION server..."

    # We need to be on the master branch
    if [ `git rev-parse --abbrev-ref HEAD` != "master" ]; then
      echo "==========Please switch to master branch before you run the deployment!========="
      exit 1
    fi

    # The git repo should be clean
    [[ $(git status -s 2> /dev/null | tail -n1) = "" ]]
    if [ $? -ne 0 ]; then
      echo "==========Git status is not clean! Please make sure there are no uncommited or untracked files before you run the deployment.==========="
      exit 1
    fi

    # We should have pushed everything
    [[ $(git diff origin/master 2> /dev/null | tail -n1) = "" ]]
    if [ $? -ne 0 ]; then
      echo "==========Your branch is ahead of origin/master. Please push your commits.==========="
          exit 1
    fi

  else
    echo "Deploying to non production servers, skipping checks"
  fi
fi

if [ $1 == 'monitor' ]; then # Production server
    CERT_FILE=~/certs/NagiosCacti-Pro.pem
    SSH_OPTS="-F ../ssh_config"
elif [ $1 == 'nagios-test' ]; then # Test server
    CERT_FILE=~/certs/TestNagios.pem
    SSH_OPTS="-F ../ssh_config"
fi

# DEPLOY_TARGET should be nagios etc path
DEPLOY_TARGET=root@$1.foxitcloud.com:/usr/local/nagios/etc/
echo Deploying to $DEPLOY_TARGET, using command: ssh $SSH_OPTS ...

# Was -avcz
# -n: Dry run
DRY_RUN_OPS=
# Rsync options: (don't use -a, which includes a bunch of things to preserve permissions/ownership, etc.
#  -r Recursive
#  -l Copy symlinks as symlinks
#  -v Verbose
#  -z Compress
#  -c Skip based on checksum, not mod-time & size

rsync $DRY_RUN_OPS  -rl -vzc \
	--rsh="ssh $SSH_OPTS" \
	./nagios_server/ \
	$DEPLOY_TARGET

#Check configuration and restart nagios
ssh $SSH_OPTS root@$1.foxitcloud.com \
    'bash -s' < post_deploy_nagios.sh
